package comgame.scenes;

import com.almasb.fxgl.audio.AudioPlayer;
import com.almasb.fxgl.audio.Sound;
import com.almasb.fxgl.dsl.FXGL;
import javafx.animation.*;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.util.Duration;
import java.util.Objects;

public class MenuScene {
    private StackPane root;
    private static comgame.scenes.MusicManager menuMusicManager = new comgame.scenes.MusicManager();

    // 递归删除文件夹方法（放在类顶部，确保能被调用）
    private static void deleteDir(java.io.File dir) {
        if (dir == null || !dir.exists()) return;
        if (dir.isDirectory()) {
            java.io.File[] files = dir.listFiles();
            if (files != null) {
                for (java.io.File file : files) {
                    deleteDir(file);
                }
            }
        }
        dir.delete();
    }

    public MenuScene() {
        // 强制隐藏player实体，防止主菜单闪现
        if (comgame.scenes.GameScene.playerEntity != null) {
            comgame.scenes.GameScene.playerEntity.getViewComponent().setVisible(false);
        }
        initUI();
    }

    private void initUI() {
        root = new StackPane();
        root.setPrefSize(800, 600);
        root.setStyle("-fx-background-color: transparent;");
        Image backgroundImg;
        try {
            backgroundImg = new Image(Objects.requireNonNull(getClass().getResourceAsStream("/assets/textures/background.png")));
        } catch (Exception e) {
            System.err.println("背景图片加载异常: " + e.getMessage());
            backgroundImg = null;
        }
        if (backgroundImg != null) {
            ImageView background = new ImageView(backgroundImg);
            background.setFitWidth(1000);
            background.setFitHeight(750);
            TranslateTransition moveTransition = new TranslateTransition(Duration.seconds(10), background);
            moveTransition.setFromX(0);
            moveTransition.setToX(-50);
            moveTransition.setCycleCount(Animation.INDEFINITE);
            moveTransition.setAutoReverse(true);
            moveTransition.play();
            root.getChildren().add(background);
        }
        Image titleImg;
        try {
            titleImg = new Image(Objects.requireNonNull(getClass().getResourceAsStream("/assets/textures/title.png")), 600, 150, false, true);
        } catch (Exception e) {
            System.err.println("背景图片加载异常: " + e.getMessage());
            titleImg = null;
        }

        if(titleImg != null)
        {
            ImageView title = new ImageView(titleImg);
            title.setRotate(-30); // 旋转45度
            StackPane.setAlignment(title, Pos.TOP_LEFT); // 左上角
            StackPane.setMargin(title, new Insets(150, 0, 0, 0)); // 距离左上角20像素
            root.getChildren().add(title);
            // ====== 添加缩放动画 ======
            ScaleTransition scaleTransition = new ScaleTransition(Duration.seconds(1.5), title);
            scaleTransition.setFromX(1.0);
            scaleTransition.setFromY(1.0);
            scaleTransition.setToX(1.2); // 放大到1.2倍
            scaleTransition.setToY(1.2);
            scaleTransition.setAutoReverse(true); // 自动反向
            scaleTransition.setCycleCount(Animation.INDEFINITE); // 无限循环
            scaleTransition.play();
        }
        if (!comgame.scenes.MusicManager.isMenuMusicPlaying) {
            if (comgame.scenes.MusicManager.menuMusic == null)
                comgame.scenes.MusicManager.menuMusic = FXGL.getAssetLoader().loadMusic("MenuMusic.mp4");
            FXGL.getAudioPlayer().loopMusic(comgame.scenes.MusicManager.menuMusic);
            comgame.scenes.MusicManager.isMenuMusicPlaying = true;
        }
        VBox buttonBox = new VBox(50);
        buttonBox.setAlignment(Pos.CENTER);
        buttonBox.setTranslateY(150);
        java.io.File saveFile = new java.io.File("src/main/Data_save/save.json");
        AnimatedButton newGameBtn = new AnimatedButton("新的开始");
        AnimatedButton continueBtn = new AnimatedButton("继续游戏");
        AnimatedButton exitBtn = new AnimatedButton("退出游戏");
        AudioPlayer audioPlayer = FXGL.getAudioPlayer();
        Sound sound1  =  FXGL.getAssetLoader().loadSound("drop.wav");
        newGameBtn.setOnMouseClicked(e -> {
            audioPlayer.playSound(sound1);
            // 递归删除Data_save文件夹
            java.io.File dataSaveDir = new java.io.File("src/main/Data_save");
            deleteDir(dataSaveDir);
            // 若目录删除失败，单独删除save.json
            java.io.File saveFileToDelete = new java.io.File("src/main/Data_save/save.json");
            if (saveFileToDelete.exists()) saveFileToDelete.delete();
            // 强制重建空目录，防止后续存档失败
            if (!dataSaveDir.exists()) dataSaveDir.mkdirs();
            // 清空全局变量，防止自动化等状态残留
            com.almasb.fxgl.dsl.FXGL.getWorldProperties().clear();
            // 显式重置自动化相关变量，彻底防止妙蛙仙子残留
            com.almasb.fxgl.dsl.FXGL.set("auto_farm_enabled", false);
            com.almasb.fxgl.dsl.FXGL.set("auto_farm_level", "");
            com.almasb.fxgl.dsl.FXGL.set("auto_farm_interval", 2.0);
            // 彻底重置所有关键静态/单例数据
            comgame.scenes.ItemManager.resetInstance();
            if (GameScene.player != null) {
                GameScene.player.resetAll();
            }
            comgame.scenes.PlantScene.resetFarmlands();
            comgame.scenes.FishpoolScene.resetFishCounts();
            comgame.scenes.LevelData.getInstance().reset();
            comgame.scenes.FishingScene.resetFishingStage();
            comgame.scenes.AltarScene.resetAltarProgress();
            // 关键：彻底清空静态变量
            GameScene.player = null;
            GameScene.playerEntity = null;
            // 重新进入开场动画/主流程
            changeToStartAnimatedScene();
            DataSaveManager.setTutorialCompleted();
        });
        continueBtn.setOnMouseClicked(e -> {
            audioPlayer.playSound(sound1);
            comgame.scenes.DataSaveManager.loadAll();
            if(!DataSaveManager.isTutorialCompleted()) {
                changeToStartAnimatedScene();
            } else {
                // 延迟切换到GameScene，避免player实体闪现
                javafx.animation.PauseTransition delay = new javafx.animation.PauseTransition(javafx.util.Duration.millis(200));
                delay.setOnFinished(ev -> ChangeToGameScene());
                delay.play();
            }
        });
        exitBtn.setOnMouseClicked(e -> {
            FXGL.play("drop.wav");
            FXGL.getGameController().exit();
        });
        if (saveFile.exists()) {
            buttonBox.getChildren().setAll(continueBtn, newGameBtn, exitBtn);
        } else {
            buttonBox.getChildren().setAll(newGameBtn, exitBtn);
        }
        root.getChildren().add(buttonBox);
        // FXGL.getGameScene().addUINode(root); // 删除这行，避免重复添加
    }

    public StackPane getRoot() {
        return root;
    }

    private void changeToStartAnimatedScene() {
        FXGL.getGameScene().clearUINodes();
        StartAnimatedScene startScene = new StartAnimatedScene();
        FXGL.getGameScene().addUINode(startScene.getSceneRoot());
        FadeTransition fadeIn = new FadeTransition(Duration.seconds(0.5), startScene.getSceneRoot());
        fadeIn.setFromValue(0);
        fadeIn.setToValue(1);
        fadeIn.play();
    }
    private void ChangeToGameScene() {
        // 1. 清除当前菜单场景的所有UI元素
        FXGL.getGameScene().clearUINodes();

        // 2. 创建GameScene实例
        GameScene gameScene = new GameScene();

        // 3. 获取新场景的根节点并添加到游戏中
        FXGL.getGameScene().addUINode(gameScene.getSceneRoot());

        // 可选：添加场景切换动画（淡入效果）
        FadeTransition fadeIn = new FadeTransition(Duration.seconds(0.5), gameScene.getSceneRoot());
        fadeIn.setFromValue(0); // 初始完全透明
        fadeIn.setToValue(1);   // 最终完全显示
        fadeIn.play();
    }

    static class AnimatedButton extends StackPane {
        private final Rectangle bg;
        private final Text text;
        private ParallelTransition parallelTransition;
        private boolean isAnimating = false;
        public AnimatedButton(String name) {
            setPrefSize(200, 60);
            setMaxSize(200, 60);
            bg = new Rectangle(200, 60);
            bg.setFill(Color.WHITE);
            bg.setStroke(Color.BLACK);
            bg.setStrokeWidth(2);
            bg.setArcWidth(10);
            bg.setArcHeight(10);
            text = new Text(name);
            text.setFont(Font.font("Arial", 24));
            text.setFill(Color.BLACK);
            getChildren().addAll(bg, text);
            setOnMouseEntered(e -> {
                if (!isAnimating) {
                    bg.setFill(Color.LIGHTGRAY);
                    setCursor(Cursor.HAND);
                    startAnimations();
                }
            });
            setOnMouseExited(e -> {
                bg.setFill(Color.WHITE);
                setCursor(Cursor.DEFAULT);
                stopAnimations();
            });
            setOnMousePressed(e -> bg.setFill(Color.DARKGRAY));
            setOnMouseReleased(e -> bg.setFill(Color.LIGHTGRAY));
        }
        private void startAnimations() {
            isAnimating = true;
            ScaleTransition scaleTransition = createScaleAnimation();
            RotateTransition rotateTransition = createRotateAnimation();
            parallelTransition = new ParallelTransition(scaleTransition, rotateTransition);
            parallelTransition.play();
            parallelTransition.setOnFinished(e -> {
                isAnimating = false;
                setRotate(0);
            });
        }
        private ScaleTransition createScaleAnimation() {
            ScaleTransition st = new ScaleTransition(Duration.millis(300), this);
            st.setFromX(1.0);
            st.setFromY(1.0);
            st.setToX(1.3);
            st.setToY(1.3);
            st.setAutoReverse(false);
            st.setCycleCount(1);
            return st;
        }
        private RotateTransition createRotateAnimation() {
            RotateTransition rt = new RotateTransition(Duration.millis(150), this);
            rt.setFromAngle(-12);
            rt.setToAngle(9);
            rt.setAutoReverse(true);
            rt.setCycleCount(2);
            return rt;
        }
        private void stopAnimations() {
            if (parallelTransition != null) {
                parallelTransition.stop();
                Timeline resetTimeline = new Timeline(
                        new KeyFrame(Duration.millis(200),
                                new KeyValue(scaleXProperty(), 1.0),
                                new KeyValue(scaleYProperty(), 1.0),
                                new KeyValue(rotateProperty(), 0)
                        ));
                resetTimeline.setOnFinished(e -> isAnimating = false);
                resetTimeline.play();
            } else {
                setScaleX(1.0);
                setScaleY(1.0);
                setRotate(0);
                isAnimating = false;
            }
        }
    }
}  